# -*- coding: utf-8 -*-
"""
Created on Tue May 16 17:05:14 2023

@author: zh-gsyw-wn
"""
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.metrics import roc_auc_score



def plot_hist(result):
    plt.figure(figsize = (10,6))
    result.esg_score.plot(kind='hist',bins=75)
    display(result.esg_score.describe())

from sklearn.metrics import roc_curve
def ks_ca(y_true,y_pred):
    fpr,tpr,thres = roc_curve(y_true,y_pred,pos_label = 1)
    ks = (tpr-fpr).max()
    return ks

def get_auc_ks(data,label='if_overdue'):
    df7 = data.copy()
    df7['if_fengx'] = 1 - df7[label]
    auc = roc_auc_score(df7['if_fengx'], df7.esg_score)
    print('AUC:',auc)
    print('KS:',ks_ca(df7.if_fengx,df7.esg_score),ks_ca(df7.if_fengx,df7.e_score),ks_ca(df7.if_fengx,df7.s_score),ks_ca(df7.if_fengx,df7.g_score))
    
    
    
    
def plot_bar(data):
    plt.figure(figsize = (10,6))
    bins2 = data.groupby('if_overdue').esg_score.mean()
    #bins2.plot(kind='bar')
    import seaborn as sns 
    sns.barplot(x='if_overdue',y='esg_score',data=bins2.to_frame().reset_index())
    bins2.plot(c='red')
    display(bins2)
    
    
#五个等级下的风险样本分布 折线图 同时计算ks 与 auc
def plot_bad_line(data,dfjch,result):
    plt.figure(figsize = (10,6))
    data = pd.merge(dfjch[['rating_id','if_overdue_class']],result,on='rating_id')
    data['if_overdue']= data.if_overdue_class.map({'Y':1,'N':0})
    data['esg_rating'] = pd.qcut(data.esg_score,5,labels=['E','D','C','B','A'])
    bins = data.groupby('esg_rating').if_overdue.sum().sort_index(ascending=False)
    bins.plot()
    print(data.groupby('esg_rating').esg_score.mean())
    plot_bar(data)
    get_auc_ks(data,label='if_overdue')


